import {useState,useEffect,useRef} from 'react'
// import {useLocation,useNavigate,Outlet} from 'react-router-dom'
import axios from 'axios'
import { Flex , Table,Modal,Button,Input,Space} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { TableColumnsType ,InputRef, TableColumnType} from 'antd';
import type { FilterDropdownProps } from 'antd/es/table/interface';
import Highlighter from 'react-highlight-words';

interface DataType {
    key: React.Key;
    drugcode:String,//药品编码
    name: String,//名称
    size: String,//规格
    package: String,//包装
    chiacode: String,//拼音码
    unit: String,//发药单位
    MSItype: String,//医保类别
    price: Number,//价格
    inventory: Number,//库存
    expiration: Number,//有效期
  }
  
  type DataIndex = keyof DataType;
  


export default function ChiaDrugKist(){
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef<InputRef>(null);
    
    const handleSearch = (
      selectedKeys: string[],
      confirm: FilterDropdownProps['confirm'],
      dataIndex: DataIndex,
    ) => {
      confirm();
      setSearchText(selectedKeys[0]);
      setSearchedColumn(dataIndex);
    };
  
    const handleReset = (clearFilters: () => void) => {
      clearFilters();
      setSearchText('');
    };

    const getColumnSearchProps = (dataIndex: DataIndex): TableColumnType<DataType> => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
          <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
            <Input
              ref={searchInput}
              placeholder={`请输入名称`}
              value={selectedKeys[0]}
              onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
              style={{ marginBottom: 8, display: 'block' }}
            />
            <Space>
              <Button
                type="primary"
                onClick={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                icon={<SearchOutlined />}
                size="small"
                style={{ width: 90 }}
              >
                搜索
              </Button>
              <Button
                onClick={() => clearFilters && handleReset(clearFilters)}
                size="small"
                style={{ width: 90 }}
              >
                重置
              </Button>
            </Space>
          </div>
        ),
        filterIcon: (filtered: boolean) => (
          <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
        ),
        onFilter: (value, record) =>
          record[dataIndex]
            .toString()
            .toLowerCase()
            .includes((value as string).toLowerCase()),
        filterDropdownProps: {
          onOpenChange(open) {
            if (open) {
              setTimeout(() => searchInput.current?.select(), 100);
            }
          },
        },
        render: (text) =>
          searchedColumn === dataIndex ? (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          ) : (
            text
          ),
        });

      const columns: TableColumnsType<DataType> = [
        { title: '药品编码', dataIndex: 'drugcode', key: '8',width:'100px',align:'center'},
        { title: '药品名称', dataIndex: 'name', key: '9',width:'100px',align:'center',fixed: 'left',...getColumnSearchProps('name')},
        { title: '规格', dataIndex: 'size', key: '11' ,width:'100px',align:'center'},
        { title: '包装', dataIndex: 'package', key: '10',width:'100px',align:'center'},
        { title: '拼音码', dataIndex: 'chiacode', key: '12' ,width:'100px',align:'center'},
        { title: '发药单位', dataIndex: 'unit', key: '13',width:'100px',align:'center' },
        { title: '医保类别', dataIndex: 'MSItype', key: '14' ,width:'100px',align:'center'},
        { title: '零售单价', dataIndex: 'price', key: '15' ,width:'100px',align:'center'},
        { title: '药品库存', dataIndex: 'inventory', key: '16',width:'100px',align:'center'},
        { title: '剩余有效期（天）', dataIndex: 'expiration', key: '17',width:'150px',align:'center' },
        {
          title: '操作',
          key: '18',
          // fixed: 'right',
          width: 100,
          render: () => <a>action</a>,
          align:'center'
        }
      ];

    //中药数据
    let [list,setlist] = useState([])
    let getlist = async()=>{
        let {data:{lis}} =  await axios.get('http://127.0.0.1:3000/why/windex')
        lis.forEach((item:any, index:any) => {
          item.key = index;
      });
      setlist(lis);
    }
    //弹出框
    const [isModalOpen, setIsModalOpen] = useState(false);
    const btnadddrug = () => {
        setIsModalOpen(true);
    };
    const handleCancel = () => {
      setIsModalOpen(false);
    };


    useEffect(()=>{
        getlist()
    },[])

    return (
        <>
            <Modal title="选择药品" footer={null}  open={isModalOpen}  onCancel={handleCancel} width={500} >
                <Table<DataType>
                    size='small'
                    columns={columns}
                    dataSource={list}
                    scroll={{ x: 'max-content', y: 55 * 5 }}
                />
            </Modal>
            <button onClick={()=>{btnadddrug()}}>add</button>
        </>
    )
}